package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.TaskDetails1Activity;
import com.mingtu.jgspatrol.adapter.SendUndoTaskAdapter;
import com.mingtu.jgspatrol.bean.SendTaskListBean;
import com.mingtu.jgspatrol.databinding.FragmentSendUndoTaskBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

public class SendUndoTaskFragment extends BaseBindingFragment<FragmentSendUndoTaskBinding> implements LazyFragmentPagerAdapter.Laziable {
    
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private SendUndoTaskAdapter sendUndoTaskAdapter;

    public static SendUndoTaskFragment getInstance() {
        SendUndoTaskFragment fragment = new SendUndoTaskFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_send_undo_task;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        sendUndoTaskAdapter = new SendUndoTaskAdapter(context);
        if (isOpenLoadAnimation) {
            sendUndoTaskAdapter.isFirstOnly(isFirstOnly);
            sendUndoTaskAdapter.openLoadAnimation(animationType);
        }

        sendUndoTaskAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(sendUndoTaskAdapter);
        sendUndoTaskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SendTaskListBean.PageBean.ListBean listBean = sendUndoTaskAdapter.getData().get(position);
                String taskId = listBean.getId();

                if (!StringUtils.isEmpty(taskId)) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("taskId", taskId);
//                    IntentUtils.getInstance().readyGo(getActivity(), SendTaskDetailsActivity.class, bundle);

                    Bundle bundle = new Bundle();
                    bundle.putString("taskId", taskId);
                    bundle.putString("taskType", MyConstant.TASK_TYPE_SEND);
                    IntentUtils.getInstance().readyGo(getActivity(), TaskDetails1Activity.class, bundle);

                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getUndoTaskList(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getUndoTaskList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(sendUndoTaskAdapter.getData(), Constant.PAGE_SIZE);
                    getUndoTaskList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    /**
     * 我下发的-待完成的任务列表
     */
    public void getUndoTaskList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("status", 0);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_SEND_TASK_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                SendTaskListBean sendTaskListBean = new SendTaskListBean();
                                sendTaskListBean = gson.fromJson(result, SendTaskListBean.class);
                                List<SendTaskListBean.PageBean.ListBean> dataBeans = sendTaskListBean.getPage().getList();

                                try {

                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            sendUndoTaskAdapter.replaceData(dataBeans);
                                        } else {
                                            sendUndoTaskAdapter.addData(dataBeans);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });

    }

    public void refresh() {
        getUndoTaskList(1);
    }

}